<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="width: 334px;">
    <el-form-item label="电话" prop="phone">
      <el-input v-model="form.phone"></el-input>
    </el-form-item>
    <el-form-item label="姓名" prop="name">
      <el-input v-model="form.name"></el-input>
    </el-form-item>
    <el-form-item label="地址" prop="address">
      <el-input v-model="form.address"></el-input>
    </el-form-item>
    <el-form-item label="积分" prop="store">
      <el-input v-model="form.store"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click.prevent="onSubmit('form')">立即创建</el-button>
      <el-button @click="returm">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  props: ["petowner"],
  data() {
    return {
      form: {
        phone: "",
        name: "",
        address: "",
        store: "0"
      },
      rules: {
        phone: [
          { required: true, message: "请输入电话", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (/^1\d{10}$/.test(value)) {
                callback();
              } else {
                callback(new Error("手机号必须1开头的11位数字"));
              }
            }
          }
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        address: [{ required: true, message: "请输入地址", trigger: "blur" }]
      }
    };
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$emit("submit", this.form);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    returm() {
      this.$message({
        type: "success",
        message: "返回成功",
        onClose: () => {
          this.$router.push({
            name: "petowners"
          });
        }
      });
    }
  },
  watch: {
    petowner: function() {
      if (this.petowner) {
        this.form = {
          phone: this.petowner.phone,
          name: this.petowner.name,
          address: this.petowner.address,
          store: this.petowner.store
        };
      }
    }
  }
};
</script>
